package com.ebspp.client.serverManager;

import java.util.HashMap;
import java.util.Map;

import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import com.ebspp.global.General;
import com.ebspp.thrift.Identity;
import com.ebspp.thrift.ResourceType;

/**
 * It manages all the heartbeat connections.
 * 
 * @author x23pan
 *
 */
public class MsgConnManager 
{
	int mPort;
	Map<String, MsgConnection> connMap;
	IStat stat;
	
	public MsgConnManager(IStat stat)
	{
		connMap = new HashMap<String, MsgConnection>();
		mPort = General.mPort;
		this.stat = stat;
	}
	
	public synchronized boolean createMsgConn(String server)
	{
		if(connMap.get(server) != null)
			return true;
		
		try {
			MsgConnection msgConn = new MsgConnection(server, mPort, stat);
			connMap.put(server, msgConn);	
		} 
		catch (TTransportException e) {
			// TODO Auto-generated catch block
			System.err.println("Cannot init mssage connection to " + server);
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public boolean initHeartBeat(String server)
	{
		MsgConnection msgConn = connMap.get(server);
		if(msgConn == null)
			return false;
		msgConn.initHeartBeat();
		return true;
	}
	
	public boolean watch(String server, ResourceType resType, Identity wID) throws TException
	{
		MsgConnection msgConn = connMap.get(server);
		if(msgConn == null)
			if(!createMsgConn(server))
				return false;

		return msgConn.watch(resType, wID);
	}
	
	public boolean deWatch(String server, ResourceType resType, Identity wID)
	{
		MsgConnection msgConn = connMap.get(server);
		if(msgConn == null)
			return false;
		
		boolean deWatch = false;
		try {
			deWatch = msgConn.deWatch(resType, wID);
		} catch (TException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("Cannot deWatch a server");
			return deWatch;
		}	
		//it needs to clean the msgConn if it has no heartBeat operation
		return deWatch;
	}
	
	public synchronized boolean closeMsgConn(String server)
	{
		if(connMap.get(server) == null)
			return true;
		
		connMap.get(server).close();
		return true;
	}
	
	
}
